package Server.Sessions;

import java.util.Iterator;

import shared.Messages.AnswerMessage;
import shared.Messages.BeginMessage;
import shared.Messages.QuestionMessage;
import shared.Messages.TurnMessage;

public class Broadcaster extends Thread {
	private ActiveSessions activeSessions;
	private OutboundMessages outQueue;


	public Broadcaster(ActiveSessions aa, OutboundMessages o) {
		activeSessions = aa;
		outQueue = o;
		start();
	}

	public void run() {
		while (true) {
			Object s = outQueue.getMessage();// blocked
			synchronized (activeSessions) { // ActiveSessions lukku!
				Iterator<ClientSession> active = activeSessions.iterator();

				while (active.hasNext()) {
					ClientSession cli = active.next();

					if (!cli.isAlive()) {
						active.remove();
					} else if (s == null) {
						break;
					}else if(s instanceof BeginMessage){
						if(cli.player.GameNo == ((BeginMessage)s).GameNo){
							cli.sendMessage((BeginMessage)s);
						}


					}else if(s instanceof QuestionMessage){
						cli.sendMessage((QuestionMessage)s);
						System.out.println("Broadcasteris: " +((QuestionMessage) s).questionContent);
						//							}
						//						}
						//					}else if(s instanceof WinMessage){
						//						if(cli.p.GameNo == ((WinMessage)s).GameNo){
						//							cli.sendMessage((WinMessage)s);
						//						}
						//					}else if(s instanceof DcWinMessage){
						//						if(cli.p.GameNo == ((DcWinMessage)s).GameNo){
						//							cli.sendMessage((DcWinMessage)s);
						//						}
					}else if(s instanceof TurnMessage){
						if(cli.player.GameNo == ((TurnMessage)s).GameNo){
							cli.sendMessage((TurnMessage)s);
						}

					}else if(s instanceof AnswerMessage){
						cli.sendMessage((AnswerMessage)s);
					}	
				}
			}	
		}
	}
}